package org.daochong.spring.controllor;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.daochong.lang.Message;
import org.daochong.web.WebContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/locale")
public class LocaleControllor {

	@RequestMapping(value = "/messages/{keys}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> getMessage(@PathVariable String keys, HttpServletRequest request) {
		String str = keys;
		Map<String, String> map = new LinkedHashMap<String, String>();
		if (str != null) {
			Object o = request.getAttribute(WebContext.MESSAGE_ID);
			Message msg = null;
			if (o != null && o instanceof Message) {
				msg = (Message) o;
			} else {
				msg = Message.getInstance();
			}
			for (String key : str.split(",")) {
				key = key.trim();
				String m = msg.getMessage(key);
				if (m == null) {
					m = "";
				}
				map.put(key, m);
			}
		}
		return map;
	}

	@RequestMapping(value = "/message/{key}", method = RequestMethod.GET)
	@ResponseBody
	public String message(@PathVariable String key, HttpServletRequest request) {
		Object o = request.getAttribute(WebContext.MESSAGE_ID);
		Message msg = null;
		if (o != null && o instanceof Message) {
			msg = (Message) o;
		} else {
			msg = Message.getInstance();
		}

		return msg.getMessage(key);
	}
}
